package redis

import (
	"encoding/json"
	"net"
	"time"

	"github.com/gomodule/redigo/redis"
)

type Options struct {
	Address  string
	Password string
	DB       int
}

var gRedisConn redis.Conn

// Run 初始化
func Run(o *Options) error {
	/*
	   1. 通过net.Dial函数 拨号类型为tcp，地址为127.0.0.1:6379redis ip地址+端口 获得一个Conn对象
	   2. 使用该Conn对象，作为创建redigo的Conn操作对象
	*/
	c, err := net.Dial("tcp", o.Address)
	if err != nil {
		return err
	}
	read := time.Minute * 60
	writer := time.Minute * 60
	gRedisConn = redis.NewConn(c, read, writer)
	return nil
}

// Shutdown
func Shutdown() {
	if gRedisConn != nil {
		gRedisConn.Close()
	}
}

// Set 普通设置
func Set(key string, val interface{}) (err error) {
	_, err = gRedisConn.Do("SET", key, val)
	return
}

// ExSet 过期设置
func ExSet(key, sec string, val interface{}) (err error) {
	_, err = gRedisConn.Do("SET", key, val, "EX", sec)
	return
}

// SetNX json设置
func SetNX(key string, val interface{}) (err error) {
	data, _ := json.Marshal(val)
	_, err = gRedisConn.Do("SETNX", key, data)
	return
}

// GetNX json获取
func GetNX(key string, val interface{}) error {
	data, err := redis.Bytes(gRedisConn.Do("GET", key))
	if err != nil {
		return err
	}
	return json.Unmarshal(data, val)
}

// SetExpire 设置过期时间
func SetExpire(key string, time float64) (err error) {
	_, err = gRedisConn.Do("EXPIRE", key, time)
	return
}

// Get 值获取
func Get(key string) (val interface{}, err error) {
	val, err = redis.String(gRedisConn.Do("GET", key))
	return
}

// Del 值删除
func Del(key string) (err error) {
	_, err = gRedisConn.Do("DEL", key)
	return
}

// Has 值存在
func Has(key string) bool {
	ok, err := redis.Bool(gRedisConn.Do("EXISTS", key))
	if err != nil {
		return false
	}
	return ok
}
